<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>购物车</title>
    <link rel="stylesheet" href="../css/style.css" />
    <script src="../js/gouWuChe.js"></script>
</head>

<body>
    <div class="catbox">
        <table id="cartTable">
            <thead>
                <tr>
                    <th><label>
                            <input class="check-all check" type="checkbox" />&nbsp;&nbsp;全选</label></th>
                    <th>商品</th>
                    <th>单价</th>
                    <th>数量</th>
                    <th>小计</th>
                    <th>操作</th>
                </tr>
            </thead>
            <tbody>
                <!-- <tr>
                    <td class="checkbox"><input class="check-one check" type="checkbox" /></td>
                    <td class="goods"><img src="../images/1.jpg" alt="" /><span>Casio/卡西欧 EX-TR350</span></td>
                    <td class="price">5999.88</td>
                    <td class="count"><span class="reduce"></span>
                        <input class="count-input" type="text" value="1" />
                        <span class="add">+</span>
                    </td>
                    <td class="subtotal">5999.88</td>
                    <td class="operation"><span class="delete">删除</span></td>
                </tr>
                <tr>
                    <td class="checkbox"><input class="check-one check" type="checkbox" /></td>
                    <td class="goods"><img src="../images/2.jpg" alt="" /><span>Canon/佳能 PowerShot SX50 HS</span></td>
                    <td class="price">3888.50</td>
                    <td class="count"><span class="reduce"></span>
                        <input class="count-input" type="text" value="1" />
                        <span class="add">+</span>
                    </td>
                    <td class="subtotal">3888.50</td>
                    <td class="operation"><span class="delete">删除</span></td>
                </tr>
                <tr>
                    <td class="checkbox"><input class="check-one check" type="checkbox" /></td>
                    <td class="goods"><img src="../images/3.jpg" alt="" /><span>Sony/索尼 DSC-WX300</span></td>
                    <td class="price">1428.50</td>
                    <td class="count"><span class="reduce"></span>
                        <input class="count-input" type="text" value="1" />
                        <span class="add">+</span>
                    </td>
                    <td class="subtotal">1428.50</td>
                    <td class="operation"><span class="delete">删除</span></td>
                </tr>
                <tr>
                    <td class="checkbox"><input class="check-one check" type="checkbox" /></td>
                    <td class="goods"><img src="../images/4.jpg" alt="" /><span>Fujifilm/富士 instax mini 25</span></td>
                    <td class="price">640.60</td>
                    <td class="count"><span class="reduce"></span>
                        <input class="count-input" type="text" value="1" />
                        <span class="add">+</span>
                    </td>
                    <td class="subtotal">640.60</td>
                    <td class="operation"><span class="delete">删除</span></td>
                </tr> -->
            </tbody>
        </table>
        <div class="foot" id="foot">
            <a class="fl" id="deleteAll" href="javascript:;">删除</a>
            <div class="fr closing" onclick="getTotal();">结 算</div>
            <input type="hidden" id="cartTotalPrice" />
            <div class="fr total">合计：￥<span id="priceTotal">0.00</span></div>
            <div class="fr selected" id="selected">已选商品<span id="selectedTotal">0</span>件<span
                    class="arrow up">︽</span><span class="arrow down">︾</span></div>
            <div class="selected-view">
                <div id="selectedViewList" class="clearfix">
                    <div><img src="../images/1.jpg"><span>取消选择</span></div>
                </div>
                <span class="arrow">◆<span>◆</span></span>
            </div>
        </div>
    </div>
</body>
<script>
    var tbody = document.querySelector("#cartTable tbody");
    var catbox = document.getElementsByClassName("catbox")[0];
    var checkAll = document.getElementsByClassName("check-all")[0];
    // var countInpList = document.getElementsByClassName("count-input");
    var checkOneList = document.getElementsByClassName("check-one");
    var priceTotal = document.getElementById("priceTotal");
    var selectedTotal = document.getElementById("selectedTotal");

    var xhr = new XMLHttpRequest();
    xhr.open("get", "../data/shoppingCar.json", true);
    xhr.send();
    xhr.onreadystatechange = function () {
        if (xhr.readyState == 4 && xhr.status == 200) {
            var text = xhr.responseText;
            var shopping = JSON.parse(text);
            var html = "";
            shopping.forEach(({ goodsId, goodsName, goodsMsg, goodsImg, goodsPrice, goodsNum }) => {
                html += `<tr>
                    <td class="checkbox"><input class="check-one check" type="checkbox" /></td>
                    <td class="goods">
                        <img src="${goodsImg}" alt="" />
                        <span>${goodsMsg}</span>
                    </td>
                    <td class="price">${goodsPrice.toFixed(2)}</td>
                    <td class="count"><span class="reduce">${goodsNum > 1 ? "-" : ""}</span>
                        <input class="count-input" type="text" value="${goodsNum}" />
                        <span class="add">+</span>
                    </td>
                    <td class="subtotal">${(goodsPrice * goodsNum).toFixed(2)}</td>
                    <td class="operation">
                        <span class="delete">删除</span>
                    </td>
                </tr>`;
            });
            tbody.innerHTML = html;
        }
    }

    //输入框
    catbox.oninput = function (e) {
        var e = e || window.event;
        var target = e.target || e.srcElement;
        // 输入框
        if (target.classList.contains("count-input")) {
            //限制输入框只能输入数字且不能为0
            var reg = /^[^0]\d*$/;
            var inp = target.value;
            console.log(target.value, reg.test(inp));
            if (!(reg.test(inp))) {
                target.value = 1;
            }

            var sum = target.value * prev(parent(target)).innerText;
            next(parent(target)).innerText = sum.toFixed(2);

            // 如果大于1，减号出现，否则消失
            if (target.value > 1) {
                prev(target).textContent = "-";
            } else {
                prev(target).textContent = "";
            }

            getTotal();
        }
    }

    catbox.onclick = function (e) {
        var e = e || window.event;
        var target = e.target || e.srcElement;

        //多选
        if (target.classList.contains("check-all")) {
            var status = checkAll.checked
            for (var i = 0; i < checkOneList.length; i++) {
                checkOneList[i].checked = status;
            }

            getTotal();
        }
        //反选
        else if (target.classList.contains("check-one")) {
            checkAll.checked = isAllchecked();

            getTotal();
        }
        //增加
        else if (target.className == "add") {
            prev(target).value++;

            var sum = prev(target).value * prev(parent(target)).textContent;
            next(parent(target)).textContent = sum.toFixed(2);

            prev(prev(target)).textContent = "-";

            getTotal();
        }
        //减少
        else if (target.className == "reduce") {
            if (next(target).value != 1) {
                next(target).value--;
            }

            var sum = next(target).value * prev(parent(target)).textContent;
            next(parent(target)).textContent = sum.toFixed(2);

            if (next(target).value == 1) {
                target.textContent = "";
            }

            getTotal();

        }
        //单删
        else if (target.className == "delete") {
            var re = confirm("是否确认删除？");
            if (re) parent(parent(target)).remove();

            checkAll.checked = isAllchecked();

            getTotal();
        }
        // 多删
        else if (target.id == "deleteAll") {
            if (checkOneList.length > 0) {
                // 获取被选中的元素
                var len = document.querySelectorAll(".check-one:checked");
                //如果被选中的元素长度大于0才执行删除
                if (len.length > 0) {
                    var re = confirm("是否确认删除？");
                    for (var i = 0; i < checkOneList.length; i++) {
                        var checkOne = checkOneList[i];
                        if (checkOne.checked && re) {
                            parent(parent(checkOne)).remove();
                            i--;
                        }
                    }
                } else if (len.length == 0) {
                    confirm("请选择至少一件商品");
                }
            } else {
                confirm("还没有心仪的商品哦，快去选一下吧");
            }

            if (checkOneList.length == 0) checkAll.checked = false;

            getTotal();

        }
    }

    //反选，如果全被选中，则返回true 
    function isAllchecked() {
        var flag = true;
        for (var i = 0; i < checkOneList.length; i++) {
            if (!(checkOneList[i].checked)) {
                flag = false;
                break;
            }
        }
        return flag;
    }

    //结算函数
    function getTotal() {
        var sum = 0;
        var allPrice = 0;
        //循环判断是否被选中
        for (var i = 0; i < checkOneList.length; i++) {
            // 如果被选中，找到需要结算的元素
            if (checkOneList[i].checked) {
                var tr = parent(parent(checkOneList[i]));
                var countIpt = tr.getElementsByClassName("count-input")[0];
                var subtotalTd = tr.getElementsByClassName("subtotal")[0];
                var num = countIpt.value * 1;
                var subtotal = subtotalTd.textContent * 1;

                sum += num;
                allPrice += subtotal;
            }
        }
        selectedTotal.textContent = sum;
        priceTotal.textContent = allPrice.toFixed(2);
    }
</script>

</html>